<?

require_once 'Mail.php';
require_once 'Mail/mime.php';

function sendMail($html) {
  $hostname = php_uname('n');

  if ($hostname == "desktop") {
    $backend = "smtp";
    $params["host"] = "smtp.xxx.com";
    $params["auth"] = true;
    $params["username"] = "x@x.de";
    $params["password"] = "xxx";
  }
  else {
    $backend = "sendmail";
    $ini_params["sendmail_path"] = preg_replace("#^(.*sendmail).*$#", "\\1", ini_get("sendmail_path"));
    $params["sendmail_path"] = $ini_params["sendmail_path"];
  }

  $recipients = 'thomas@tschoen.de';

  $headers['From']    = 'thomas@tschoen.de';
  $headers['To']      = 'thomas@tschoen.de';
  $headers['Subject'] = 'Test message';

  //Mime body bauen
  $mime = new Mail_mime();

  $mime->setTXTBody($html);
  $mime->setHTMLBody($html);

  //do not ever try to call these lines in reverse order
  $body = $mime->get();
  $headers = $mime->headers($headers);

  $mail =& Mail::factory($backend, $params);
  $mail->send($recipients, $headers, $body);
}

function sendKontaktMail() {
  if($_POST) {
    $kontaktmailHtml = file_get_contents(dirname($_SERVER['SCRIPT_FILENAME']) . '/resources/kontakt.html');

    while(list($key, $value) = each($_POST)) {
      if (is_array($value)) {
        while(list($innerkey, $innervalue) = each($value)) {
          $token = '$'.$key.'['.$innerkey.']'.'$';
          $kontaktmailHtml = str_replace($token, $innervalue, $kontaktmailHtml);
        }
      }
      else {
        if (empty($value) || strlen($value) == 0) {
          $value = "&nbsp;";
        }
        $kontaktmailHtml = str_replace('$'.$key.'$', $value, $kontaktmailHtml);
      }
    }
    $kontaktmailHtml = preg_replace("#\\$[a-zA-Z0-9_\\[\\]]*\\$#", "&nbsp;", $kontaktmailHtml);
    debug($_POST);
    //sendMail($kontaktmailHtml);
  }
}

function debug($message) {
  echo('<pre>');
  print_r($message);
  echo('</pre>');
}

?>